package weiyao.Detector;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
import weiyao.GUI.ScanResultCallback;

import java.util.List;

public class CsrfDetector extends BaseDetector {

    @Override
    public void detect(Page page, String baseUrl, ScanResultCallback callback) {
        Html html = page.getHtml();
        List<String> formElements = html.xpath("//form").all();

        for (String formHtml : formElements) {
            Html form = new Html(formHtml);

            boolean hasCsrfToken = form.xpath("//input[contains(@name, 'csrf')]").match() ||
                    form.xpath("//input[contains(@name, 'token')]").match() ||
                    form.xpath("//input[contains(@name, 'nonce')]").match();

            if (!hasCsrfToken) {
                // 获取表单的action属性
                String action = form.xpath("//form/@action").get();

                // 如果action为空，使用当前页面URL
                String formUrl = (action != null && !action.isEmpty()) ?
                        action : page.getUrl().get();

                // 确保URL是绝对路径
                String absoluteUrl = makeAbsoluteUrl(baseUrl, formUrl);

                // 获取表单方法
                String method = form.xpath("//form/@method").get() != null ?
                        form.xpath("//form/@method").get() : "GET";

                // 生成格式化的漏洞详情 - 添加载荷信息
                String tokenStatus = "缺失CSRF令牌"; // 更明确的变量名
                String details = "潜在的CSRF漏洞!\n" +
                        "URL: " + absoluteUrl + "\n" +
                        "方法: " + method + "\n" +
                        "载荷: " + tokenStatus;  // 这里"载荷"实际表示令牌状态

                callback.onVulnerabilityFound("CSRF", details);
            }
        }
    }
}